<template>
  <confirm-bar :visible="downloadBarVisible">
    <template #content>
      已选&nbsp;{{ selectedRowKeys.length }}&nbsp;项
    </template>
    <template #handle>
      <a-button type="link" @click="onCancel">取消选择</a-button>
      <a-button
        type="link"
        @click="onConfirm"
        :loading="loading"
        :disabled="selectedRowKeys.length === 0"
      >
        确认下载
      </a-button>
    </template>
  </confirm-bar>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import ConfirmBar from '@/components/confirm-bar/confirm-bar.vue'
import {
  useRowSelectionActive,
  useRowSelection,
  useLockForInUse,
  useDownloadBarVisible,
} from './provide-context.js'
import { downloadFile } from '@/api/db.js'
import { downloadFormBlob } from '@/utils/util.js'
/**
 * 全局
 */
let rowSelectionActive = useRowSelectionActive()
let rowSelection = useRowSelection()
let { selectedRowKeys, selectedRows } = rowSelection
let lockForInUse = useLockForInUse()
let downloadBarVisible = useDownloadBarVisible()
/**
 * 操作逻辑
 */
let loading = ref(false)
function onCancel() {
  downloadBarVisible.value = false
  rowSelectionActive.value = false
  lockForInUse.value = null
  delete rowSelection.getCheckboxProps
}
async function onConfirm() {
  loading.value = true
  try {
    selectedRows.value.forEach(item => {
      let type =
        item.isPersonal === 1
          ? 'personal'
          : item.isPersonal === 2
            ? 'library'
            : ''
      downloadFile({ id: item?.id }, type)
        .then(downloadFormBlob)
        .catch(() => {
          message.error(`导出失败<${item?.id}>`)
        })
    })
    downloadBarVisible.value = false
    rowSelectionActive.value = false
    lockForInUse.value = null
    delete rowSelection.getCheckboxProps
  } catch (e) {}
  loading.value = false
}
</script>
